const { model } = require('mongoose')
const { complaintsModel } = require('./models/complaintsModel')
const{ lessorsModel } = require("./models/lessorsModel")
const { tenantsModel } =require("./models/tenantsModel")
module.exports.getComplaints = async function(msg){
    const { currentPage,pageSize,content,date} = msg
    const total = (await complaintsModel.find({content: { $regex: content, $options: '$i' },date:{ $regex: date, $options: '$i' }})).length
    const pages = Math.ceil(total / msg.pageSize);
    const data = await complaintsModel.find({content: { $regex: content, $options: '$i' },date:{ $regex: date, $options: '$i' }}).populate('name').populate('cplTarget').limit(msg.pageSize - 0).skip((msg.currentPage - 1) * msg.pageSize);
    return {data,total,pages}
} 

module.exports.getComplaints2 = async function (msg){
    const { currentPage,pageSize,content,date} = msg
    const total = (await complaintsModel.find({state:true,content: { $regex: content, $options: '$i' },date:{ $regex: date, $options: '$i' }})).length
    const data = await complaintsModel.find({state:true,content: { $regex: content, $options: '$i' },date:{ $regex: date, $options: '$i' }}).populate('name').populate('cplTarget').limit(msg.pageSize - 0).skip((msg.currentPage - 1) * msg.pageSize);
    const pages = Math.ceil(total / msg.pageSize);
    return {data,total,pages}
}
module.exports.getComplaints3 = async function (msg){
    const { currentPage,pageSize,content,date} = msg
    const total = (await complaintsModel.find({state:false,content: { $regex: content, $options: '$i' },date:{ $regex: date, $options: '$i' }})).length
    const data = await complaintsModel.find({state:false,content: { $regex: content, $options: '$i' },date:{ $regex: date, $options: '$i' }}).populate('name').populate('cplTarget').limit(msg.pageSize - 0).skip((msg.currentPage - 1) * msg.pageSize);
    const pages = Math.ceil(total / msg.pageSize);
    return {data,total,pages}
}
module.exports.getComplaintsById=async function(msg){
    const data = await complaintsModel.findById({_id:msg._id}).populate('name').populate('cplTarget')
    return data
}

module.exports.minusLessorsCredits= async function(msg){
    const obj = await lessorsModel.findById(msg._id)
    var credits = obj.credits-msg.point
    const data = await lessorsModel.findOneAndUpdate({_id:msg._id},{credits:credits})
    return data
}
module.exports.minusTenantsCredits= async function(msg){
    const obj = await tenantsModel.findById(msg._id)
    var credits = obj.credits-msg.point
    const data = await tenantsModel.findOneAndUpdate({_id:msg._id},{credits:credits})
    return data
}

module.exports.handleComplaints = async function(msg){
    console.log(msg)
    const data = await complaintsModel.findOneAndUpdate({_id:msg._id},{results:msg.content,state:true})
    return data
}